package com.sneakxy.cloudbase.platform.utils;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.sneakxy.cloudbase.platform.utils.web.Response;

public class BindingResultUtils {

	public static Map<String, String> getFieldErrors(BindingResult result) {
		Map<String, String> errors = new LinkedHashMap<>();
		Iterator<FieldError> it = result.getFieldErrors().iterator();
		FieldError error = null;
		while(it.hasNext()) {
			error = it.next();
			errors.put(error.getField(), error.getDefaultMessage());
		}
		return errors;
	}
	
	public static Response<Map<String, String>> getFieldErrorsResponse(BindingResult result) {
		Map<String, String> error = getFieldErrors(result);
		return Response.fail(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "提交参数错误", error);
	}
	
	private BindingResultUtils() {}
	
}
